<?php

namespace App\Services\ApplyGoldCoinWithdrawMyBank;

use App\Models\Withdraw;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplyGoldCoinWithdrawMyBankRequest extends FormRequest
{
	public function rules()
	{
		$user = $this->user();
		if (! $user->cert_number) {
			fail('请先绑定银行卡账号');
		} elseif (! $user->pay_code) {
			fail('请先设置交易密码');
		} /*elseif ($user->isWithdrawDangerBySandpay()) {
			fail('资金安全指数较低请联系客服确认');
		}*/

		return [
			'coins' => [
				'required',
				'numeric',
				'min:1',
				$this->coins()
			],
			'pay_code' => [
				'nullable',
				'string',
				'min:6',
				$this->paycode()
			],

		];
	}

	public function coins()
	{
		return function ($key, $value, $fail) {
			if ($value <= 0) {
				return $fail('请输入正确的提现金额');
			} elseif (! $this->isWithdrawTimeAllowed()) {
				return $fail('银行卡提现需每日'.$this->withdrawTimeAllowedRange().'进行申请。');
			} elseif ($this->user()->gold_coins <= 0) {
				return $fail('可提现余额不足');
			} elseif (! $this->isWithdrawOn()) {
				return $fail('平台尚未开放提现功能');
			} elseif (! $this->user()->isBankBound()) {
				return $fail('提现银行卡未绑定');
			} elseif (! $this->isStormSupportMatched()) {
				return $fail('扶持用户100元以上部分可提现');
			} elseif (! $this->isLowestAmountMatched()) {
				return $fail("提现金额必须大于 '{$this->allowedLowestAmount()}'");
			}  elseif (! $this->isHighestAmountMatched()) {
				return $fail("提现金额必须小于 '{$this->allowedHighestAmount()}'");
			}  elseif (! $this->isGoldCoinsEnough()) {
				return $fail('可提现余额不足');
			}  else {
				return true;
			}
		};
	}

	protected function withdrawTimeAllowedRange()
	{
		return Withdraw::withdrawTimeAllowedRange();
	}

	protected function isWithdrawTimeAllowed()
	{
		return Withdraw::isWithdrawTimeAllowed();
	}

	protected function isStormSupportMatched(): bool
	{
        $supportCoins = cs('storm')->gold_support_coins;

        if ($supportCoins <= 0) return true;

		/**
		 * @var User $user
		 */
		$user = $this->user();

		$hasSupported = $user->goldCoins()->where('remark', 'support_gold_coins')->exists();

		if (!$hasSupported) return true;

		$isLeftCoinsMatched = big_decimal($user->gold_coins)->minus($this->coins)->isGreaterThanOrEqualTo($supportCoins);

		if ($isLeftCoinsMatched) return true;

		return false;
	}

	protected function isWithdrawOn()
	{
		return Withdraw::isWithdrawOn();
	}

	protected function allowedLowestAmount()
	{
		return Withdraw::allowedLowestAmount();
	}

	protected function isLowestAmountMatched()
	{
		return Withdraw::isLowestAmountMatched($this->coins);
	}

	protected function allowedHighestAmount()
	{
		return Withdraw::allowedHighestAmount();
	}

	protected function isHighestAmountMatched()
	{
		return Withdraw::isHighestAmountMatched($this->coins);
	}

	protected function isGoldCoinsEnough()
	{
		return Withdraw::isCoinsEnoughToDeduct($this->user(), $this->coins);
	}



}
